package com.baosight.risk.service.rire.impl;

import com.baosight.risk.api.rire.RireReportWordService;
import com.baosight.risk.api.riri.IRiriRiskService;
import com.baosight.risk.api.xtaa.code.IXtaaCodeService;
import com.baosight.risk.api.xtzy.IXtzyCompanyService;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.riim.RiimRiskImportMapper;
import com.baosight.risk.mapper.rire.RireRiskEventMapper;
import com.baosight.risk.mapper.rire.RireRiskTargetMapper;
import com.baosight.risk.mapper.rire.RireRiskWarningStatusMapper;
import com.baosight.risk.mapper.riri.RiriRiskMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringRuleMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringStatusMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringTargetMapper;
import com.baosight.risk.mapper.xtdc.XtdcAttachMapper;
import com.baosight.risk.mapper.xtzy.XtzyCompanyMapper;
import com.baosight.risk.mapper.xtzy.XtzyOrgMapper;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.riim.vo.RiimRiskImportVO;
import com.baosight.risk.service.rire.entity.RireRiskEvent;
import com.baosight.risk.service.rire.entity.RireRiskTarget;
import com.baosight.risk.service.rire.entity.RireRiskWarningStatus;
import com.baosight.risk.service.rire.vo.RireRiskEventVO;
import com.baosight.risk.service.riri.entity.RiriRisk;
import com.baosight.risk.service.riri.vo.RiskTopThreeVO;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaring;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringRule;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringStatus;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringTarget;
import com.baosight.risk.service.xtaa.code.entity.XtaaCode;
import com.baosight.risk.service.xtdc.entity.XtdcAttach;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyOrg;
import com.baosight.risk.service.xtzy.impl.XtzyCompanyServiceImpl;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class RireReportWordServiceImpl extends BaseServiceImpl<RiimRiskImport> implements RireReportWordService {

    @Autowired
    private RiimRiskImportMapper riskImportMapper;
    @Autowired
    private RireRiskTargetMapper rireRiskTargetMapper;
    @Autowired
    private RireRiskEventMapper rireRiskEventMapper;
    @Autowired
    private RireRiskWarningStatusMapper rireRiskWarningStatusMapper;
    @Autowired
    private RiriRiskMapper ririRiskMapper;
    @Autowired
    private RiwaRiskWaringStatusMapper riskWaringStatusMapper;
    @Autowired
    private RiwaRiskWaringRuleMapper riskWaringRuleMapper;

    @Autowired
    private XtdcAttachMapper xtdcAttachMapper;
    @Autowired
    private RiwaRiskWaringMapper riskWaringMapper;
    @Autowired
    private XtzyCompanyMapper xtzyCompanyMapper;
    @Autowired
    private RiwaRiskWaringTargetMapper riskWaringTargetMapper;

    @Autowired
    private IXtzyCompanyService xtzyCompanyService;

    @Autowired
    private IRiriRiskService ririRiskService;

    @Autowired
    private IXtaaCodeService xtaaCodeService;

    @Autowired
    private XtzyOrgMapper xtzyOrgMapper;

    @Override
    public Map reportWordList(List<String> reportIds) throws Exception {
        Map map = new HashMap();
        RireRiskWarningStatus status = rireRiskWarningStatusMapper.selectByPrimaryKey(reportIds.get(0));
        //全年重点风险
        RiimRiskImportVO riskImport = new RiimRiskImportVO();
        riskImport.setAcctYear(status.getAcctYear());
        riskImport.setIsOverTheYears("Y");
        riskImport.setManageCompCode(status.getManageCompCode());
        List<RiimRiskImport> importList = riskImportMapper.selectList(riskImport);
        //全年重点风险集合
        List<Map> mlist = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(importList)) {
            importInfo(mlist, importList);
        }
        map.put("m", mlist);
        //历年重点风险==就是没有结题的重点风险（且不在今年的重点风险清单内）
        List<RiimRiskImport> oldImportList = riskImportMapper.oldImportList(status.getAcctYear(),status.getManageCompCode());
        List<Map> lmlist = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(oldImportList)) {
            importInfo(lmlist, oldImportList);
        }
        map.put("lm", lmlist);
        //主要风险事件披露
        List<RireRiskEvent> eventList = rireRiskEventMapper.queryByReportIds(reportIds);
        List<Map> elist = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(eventList)) {
            for (RireRiskEvent event : eventList) {
                Map eMap = new HashMap();
                eMap.put("eventName", StringUtils.isEmpty(event.getEventName()) ? " " : zhaunhuan(event.getEventName()));
                eMap.put("eventDesc", StringUtils.isEmpty(event.getEventDesc()) ? " " : zhaunhuan(event.getEventDesc()));
                eMap.put("riskName", StringUtils.isEmpty(event.getExt3()) ? "暂无风险" : zhaunhuan(event.getExt3()));
                eMap.put("now", getColorName(StringUtils.isEmpty(event.getExt1()) ? "/色" : zhaunhuan(event.getExt1())));
                eMap.put("next", getColorName(StringUtils.isEmpty(event.getExt2()) ? "/色" : zhaunhuan(event.getExt2())));
                eMap.put("effectDesc", StringUtils.isEmpty(event.getEffectDesc()) ? " " : zhaunhuan(event.getEffectDesc()));
                eMap.put("strategy", StringUtils.isEmpty(event.getStrategy()) ? " " : zhaunhuan(event.getStrategy()));
                elist.add(eMap);
            }
        } else {
            Map eMap = new HashMap();
            eMap.put("eventName", "暂无");
            eMap.put("eventDesc", "暂无");
            eMap.put("riskName", "暂无风险");
            eMap.put("now", getColorName("/色"));
            eMap.put("next", getColorName("/色"));
            eMap.put("effectDesc", "暂无");
            eMap.put("strategy", "暂无");
            elist.add(eMap);
        }

        map.put("e", elist);
        //部门top3风险评估
        List<RiriRisk> riskList = Lists.newArrayList();
        //查询所有参与自评的单位
        List<XtzyCompany> riskCompany = xtzyCompanyMapper.selectCompanyLikeCompCode(status.getManageCompCode());
        for (XtzyCompany xtzyCompany : riskCompany) {
            RiskTopThreeVO riskTopThree = new RiskTopThreeVO();
            riskTopThree.setAcctYear(status.getAcctYear());
            riskTopThree.setQuarterCurrent(status.getQuarterCode());
            riskTopThree.setCompCode(xtzyCompany.getCompCode());
            //查询本单位及下属子公司的风险自评top3
            List<RiriRisk> risks = ririRiskService.getTopThree(riskTopThree);
            if (CollectionUtils.isNotEmpty(risks)) {
                riskList.addAll(risks);
            } else {
                // 该单位零报告
                RiriRisk ririRisk = new RiriRisk();
                ririRisk.setDeptName(xtzyCompany.getCompName());
                ririRisk.setExt1("zero");
                riskList.add(ririRisk);
            }
        }

        List<Map> rlist = new ArrayList<>();
        int index = 0;
        if (CollectionUtils.isNotEmpty(riskList)) {
            for (RiriRisk risk : riskList) {
                Map rMap = new HashMap();
                rMap.put("index", index += 1);
                String dName=risk.getDeptName();
                if (StringUtils.isEmpty(dName)){
                    dName=" ";
                }else{
                    dName=zhaunhuan(dName).replaceAll("\u001C", "");
                }
                rMap.put("deptName",dName);
                rMap.put("aa", "/");
                if ("zero".equals(risk.getExt1())) {
                    // 零报告
                    rMap.put("riskName", "零报告");
                    rMap.put("riskDesc", "/");
                    rMap.put("remark", "/");
                } else {
                    rMap.put("riskName", StringUtils.isEmpty(risk.getRiskName()) ? " " : zhaunhuan(risk.getRiskName()).replaceAll("\u001C", ""));
                    rMap.put("riskDesc", StringUtils.isEmpty(risk.getRiskDesc()) ? " " : zhaunhuan(risk.getRiskDesc()).replaceAll("\u001C", ""));
                    rMap.put("remark", StringUtils.isEmpty(risk.getRemark()) ? " " : zhaunhuan(risk.getRemark()).replaceAll("\u001C", ""));
                }
                rlist.add(rMap);
            }

//            Map<String, List<RiriRisk>> riskMap = riskList.stream().collect(Collectors.groupingBy(RiriRisk::getDeptCode));
//            for (String deptCode : riskMap.keySet()) {
//                List<RiriRisk> risks = riskMap.get(deptCode);
//                for (RiriRisk risk : risks) {
//                    Map rMap = new HashMap();
//                    rMap.put("index", index += 1);
//                    rMap.put("deptName", StringUtils.isEmpty(risk.getDeptName()) ? " " : zhaunhuan(risk.getDeptName()).replaceAll("\u001C", ""));
//                    rMap.put("riskName", StringUtils.isEmpty(risk.getRiskName()) ? " " : zhaunhuan(risk.getRiskName()).replaceAll("\u001C", ""));
//                    rMap.put("riskDesc", StringUtils.isEmpty(risk.getRiskDesc()) ? " " : zhaunhuan(risk.getRiskDesc()).replaceAll("\u001C", ""));
//                    rMap.put("remark", StringUtils.isEmpty(risk.getRemark()) ? " " : zhaunhuan(risk.getRemark()).replaceAll("\u001C", ""));
//                    rMap.put("aa", "/");
//                    rlist.add(rMap);
//                }
//            }
        } else {
            Map rMap = new HashMap();
            rMap.put("index", "/");
            rMap.put("deptName", "/");
            rMap.put("riskName", "/");
            rMap.put("riskDesc", "/");
            rMap.put("remark", "/");
            rMap.put("aa", "/");
            rlist.add(rMap);
        }
        map.put("r", rlist);

        //附件披露报告
        List<Map> mapList = new ArrayList<>();
        int sum = 0;
        for (String reportId : reportIds) {
            Map map1 = reportWord(reportId, "1");
            map1.put("index", sum += 1);
            // 分页符
            if (sum != reportIds.size()) {
                map1.put("pageSplit", pageSplit);
            }
            mapList.add(map1);
        }
        XtzyOrg orgParam=new XtzyOrg();
        orgParam.setBusiCompCode(status.getManageCompCode());
        XtzyOrg orgData =xtzyOrgMapper.selectOne(orgParam);
        map.put("orgName", orgData.getBusiOrgNameLong());
        map.put("list", mapList);
        map.put("size", mapList.size());
        map.put("acctYear", status.getAcctYear());
        map.put("quarter", status.getQuarterCode());
        map.put("manageCompName",status.getManageCompName());
        map.put("date", zhaunhuan(DateUtils.format(new Date(), "yyyy年MM月dd日")));
        return map;
    }


    public void importInfo(List<Map> mapList, List<RiimRiskImport> importList) {
        int i = 0;
        for (RiimRiskImport riimRiskImport : importList) {
            Map mMap = new HashMap();
            mMap.put("index", i += 1);
            mMap.put("riskName", StringUtils.isEmpty(riimRiskImport.getRiskName()) ? "/" : zhaunhuan(riimRiskImport.getRiskName()));
            mMap.put("deptName", StringUtils.isEmpty(riimRiskImport.getDeptName()) ? "/" : zhaunhuan(riimRiskImport.getDeptName()));
            List<RireRiskWarningStatus> statusList = rireRiskWarningStatusMapper.getWarningStatusByImportId(riimRiskImport.getId(), null, null);
            String color = getColorName("/");
            if (CollectionUtils.isNotEmpty(statusList)) {
                for (RireRiskWarningStatus rireRiskWarningStatus : statusList) {
                    if ("1".equals(rireRiskWarningStatus.getQuarterCode())) {
                        mMap.put("one", getColorName(StringUtils.isEmpty(rireRiskWarningStatus.getWaringStatus()) ? "/" : rireRiskWarningStatus.getWaringStatus()));
                    } else if ("2".equals(rireRiskWarningStatus.getQuarterCode())) {
                        mMap.put("two", getColorName(StringUtils.isEmpty(rireRiskWarningStatus.getWaringStatus()) ? "/" : rireRiskWarningStatus.getWaringStatus()));
                    } else if ("3".equals(rireRiskWarningStatus.getQuarterCode())) {
                        mMap.put("three", getColorName(StringUtils.isEmpty(rireRiskWarningStatus.getWaringStatus()) ? "/" : rireRiskWarningStatus.getWaringStatus()));
                    } else {
                        mMap.put("four", getColorName(StringUtils.isEmpty(rireRiskWarningStatus.getWaringStatus()) ? "/" : rireRiskWarningStatus.getWaringStatus()));
                    }
                }
            } else {
                mMap.put("one", color);
                mMap.put("two", color);
                mMap.put("three", color);
                mMap.put("four", color);
            }
            if (null == mMap.get("one")) {
                mMap.put("one", color);
            }
            if (null == mMap.get("two")) {
                mMap.put("two", color);
            }
            if (null == mMap.get("three")) {
                mMap.put("three", color);
            }
            if (null == mMap.get("four")) {
                mMap.put("four", color);
            }
            mapList.add(mMap);
        }
    }

    /**
     * 导出披露报告word
     *
     * @param reportId 披露报告ID
     * @return
     */
    @Override
    public Map reportWord(String reportId, String flag) throws Exception {
        Map map = new HashMap();
        RireRiskWarningStatus status = rireRiskWarningStatusMapper.selectByPrimaryKey(reportId);
        if (null == status) {
            throw new Exception("披露报告不存在，无法导出word文档！");
        }
        RiimRiskImport riskImport = riskImportMapper.selectByPrimaryKey(status.getImportGuid());
        RireRiskEventVO eventVo=new RireRiskEventVO();
        eventVo.setImportGuid(riskImport.getId());
        List<RireRiskEvent> eventListReport=rireRiskEventMapper.queryRiskEventData(eventVo);

        map.put("riskName", StringUtils.isEmpty(riskImport.getRiskName()) ? " " : zhaunhuan(riskImport.getRiskName()));
        map.put("dutyCompName", StringUtils.isEmpty(riskImport.getDeptName()) ? " " : zhaunhuan(riskImport.getDeptName()));
        map.put("auxiliaryCompName", StringUtils.isEmpty(riskImport.getAuxiliaryCompName()) ? " " : zhaunhuan(riskImport.getAuxiliaryCompName()));
        map.put("createTime", (null == DateUtils.format(new Date(), "yyyy年MM月dd日") ? " " : DateUtils.format(new Date(), "yyyy年MM月dd日")));
        map.put("riskDesc", StringUtils.isEmpty(riskImport.getRiskDesc()) ? " " : zhaunhuan(riskImport.getRiskDesc()));
        String specialFlag = StringUtils.isEmpty(riskImport.getSpecialFlag()) ? "Y" : riskImport.getSpecialFlag();
        // 是否专项推进
        if("Y".equals(specialFlag)){
            // 专项推进项目==推进目标
            map.put("ext1", StringUtils.isEmpty(status.getExt1()) ? new String[]{""}  : zhaunhuan(status.getExt1()).split("\n"));
            //存在问题及需协调事项
            map.put("ext2", StringUtils.isEmpty(status.getExt2()) ? new String[]{""}  : zhaunhuan(status.getExt2()).split("\n"));
            // 专项推进项目==本季度推进情况
            map.put("strategy", StringUtils.isEmpty(status.getStrategy()) ? new String[]{""}  : zhaunhuan(status.getStrategy()).split("\n"));
            // 是否受控
            map.put("waringStatus", StringUtils.isEmpty(status.getWaringStatus()) ? "" : getColorName(status.getWaringStatus(), conclusionMap));
            map.put("nextWaringStatus", StringUtils.isEmpty(status.getNextWaringStatus()) ? "" : getColorName(status.getNextWaringStatus(), conclusionMap));
        }else {
            map.put("ext1", StringUtils.isEmpty(status.getExt1()) ? " " : zhaunhuan(status.getExt1()));
            map.put("strategy", StringUtils.isEmpty(status.getStrategy()) ? " " : zhaunhuan(status.getStrategy()));
            map.put("waringStatus", StringUtils.isEmpty(status.getWaringStatus()) ? "" : getColorName(status.getWaringStatus()));
            map.put("nextWaringStatus", StringUtils.isEmpty(status.getNextWaringStatus()) ? "" : getColorName(status.getNextWaringStatus()));
        }
        map.put("specialFlag", specialFlag);
        map.put("aa", " ");
        map.put("bb", " ");
        map.put("acctYear", StringUtils.isEmpty(status.getAcctYear()) ? " " : zhaunhuan(status.getAcctYear()));
        map.put("quarter", StringUtils.isEmpty(status.getQuarterCode()) ? " " : zhaunhuan(status.getQuarterCode()));
        String createBy = (StringUtils.isEmpty(status.getEditPerson()) ? " " : zhaunhuan(status.getEditPerson())).trim();

        int maxSize = 24;

        int length = createBy.length() * 2;

        if (length <= maxSize) {
            for (int i = 0; i < maxSize - length; i++) {
                createBy += " ";
            }
        }

        map.put("createBy", createBy);

        String groupUserName = (StringUtils.isEmpty(status.getGroupUserName()) ? " " : zhaunhuan(status.getGroupUserName())).trim();

        length = groupUserName.length() * 2;

        if (length <= maxSize) {
            for (int i = 0; i < maxSize - length; i++) {
                groupUserName += " ";
            }
        }

        map.put("groupUserName", groupUserName);
        map.put("deptUserName", StringUtils.isEmpty(status.getDeptUserName()) ? " " : zhaunhuan(status.getDeptUserName()));
        //如果是专项推进项目，就没有必要执行下面的代码，直接返回
        if ("Y".equals(riskImport.getSpecialFlag())) {
            map.put("eventList", this.eventListData(status.getId()));
            return map;
        }
        //风险预警区间
        //根据披露报告和重点风险找到预警模型
        List<RiwaRiskWaring> waringList = riskWaringMapper.getWaringByImportId(status.getId());
        String waring = "";
        String warningType = "";
        List<XtdcAttach> attachList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(waringList)) {
            Integer index = 0;
            for (RiwaRiskWaring riwaRiskWaring : waringList) {
                index += 1;
                waring += StringUtils.isNotEmpty(riwaRiskWaring.getWarningDesc())? riwaRiskWaring.getWarningDesc()+ "\n": "";
                warningType = riwaRiskWaring.getWarningType();
                //找到预计模型附件图片
                List<XtdcAttach> attaches = xtdcAttachMapper.selectBySourceGuid(riwaRiskWaring.getId());
                if (CollectionUtils.isNotEmpty(attaches)) {
                    attachList.addAll(attaches);
                }
            }
        }
        map.put("warningType", warningType);
        map.put("waringDesc", StringUtils.isEmpty(waring) ? new String[]{""} : zhaunhuan(waring).split("\n"));
        //本期风险应对措施
        map.put("strategyList", StringUtils.isEmpty(status.getStrategy()) ? new String[]{""} : zhaunhuan(status.getStrategy()).split("\n"));
        //下期风险预判依据
        map.put("warningAccording", StringUtils.isEmpty(status.getWarningAccording()) ? "" : zhaunhuan(status.getWarningAccording()));
        //本期风险事件披露
        map.put("eventList", this.eventListData(status.getId()));
        //附件处理
        List<Map> imageList = new ArrayList<>();
        if (CollectionUtils.isEmpty(attachList)) {
        } else {
            for (XtdcAttach xtdcAttach : attachList) {
                Map imageMap = new HashMap();
                String image = getImageStr(xtdcAttach.getFilePath());
//                if (StringUtils.isNotEmpty(image)) {
                    imageMap.put("image", image);
                    imageList.add(imageMap);
//                }
            }
        }
        map.put("images", imageList);
        //指标处理，找到当前披露报告的所有指标
        List<RireRiskTarget> targetList = rireRiskTargetMapper.getTargetByImportId(status.getId());
        List<Map> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(targetList)) {
            Map<String, Object> targetMap = new HashMap<>();
            targetMap.put("targetTypeName", "暂无");
            targetMap.put("targetName", "暂无");
            targetMap.put("standdardValue", "暂无");
            targetMap.put("targetValue", "暂无");
            targetMap.put("waringStatus", "暂无");
            targetMap.put("nextWaringStatus", "暂无");
            list.add(targetMap);
        }
        if (CollectionUtils.isNotEmpty(targetList)) {
            for (RireRiskTarget target : targetList) {
                Map<String, Object> targetMap = new HashMap<>();
                targetMap.put("targetTypeName", StringUtils.isEmpty(target.getTargetClassName()) ? " " : zhaunhuan(target.getTargetClassName()));
                String targetName = StringUtils.isEmpty(target.getTargetName()) ? " " : zhaunhuan(target.getTargetName());
                if ("Y".equals(target.getCompFlag()) && StringUtils.isNotEmpty(target.getCompName())) {
                    targetName = target.getCompName() + "："+ targetName;
                }
                targetMap.put("targetName", targetName);
                // 值集类型
                if ("C".equals(target.getQuantityFlag())) {
                    String standdardValue = StringUtils.isEmpty(target.getStandardValue()) ? " " : target.getStandardValue();
                    String targetValue = StringUtils.isEmpty(target.getTargetValue()) ? " " : target.getTargetValue();
                    List<XtaaCode> codeList = xtaaCodeService.selectDataByDDTypeCode(target.getDdTypeCode());
                    for (XtaaCode xtaaCode : codeList) {
                        if (xtaaCode.getDdCode().equals(standdardValue)) {
                            targetMap.put("standdardValue", StringUtils.isEmpty(xtaaCode.getDdName())? " " : xtaaCode.getDdName());
                        }
                        if (xtaaCode.getDdCode().equals(targetValue)) {
                            targetMap.put("targetValue", StringUtils.isEmpty(xtaaCode.getDdName())? " " : xtaaCode.getDdName());
                        }
                    }
                } else {
                    String standdardValue = StringUtils.isEmpty(target.getStandardValue()) ? " " : target.getStandardValue();
                    if (StringUtils.isNotEmpty(standdardValue)) {
                        standdardValue += target.getUnit();
                    }
                    targetMap.put("standdardValue", standdardValue);
                    String targetValue = StringUtils.isEmpty(target.getTargetValue()) ? " " : target.getTargetValue();
                    if (StringUtils.isNotEmpty(targetValue)) {
                        targetValue += target.getUnit();
                    }
                    targetMap.put("targetValue", targetValue);
                }
                list.add(targetMap);
            }
        }
        //找到预警区间，根据披露报告找到披露状态
        //找到披露报告
        List<Map> statusList = new ArrayList<>();
        List<RiwaRiskWaring> riskWaringList = riskWaringMapper.getWaringByImportId(status.getId());
        for (RiwaRiskWaring waring1 : riskWaringList) {
            List<RiwaRiskWaringStatus> waringStatusList = riskWaringStatusMapper.getWaringStatusByWaringId(waring1.getId());
            for (RiwaRiskWaringStatus waringStatus : waringStatusList) {
                Map<String, Object> statusMap = new HashMap<>();
                statusMap.put("waringStatus", getColorName(waringStatus.getWarningStatus(), colorMap2));

                String s1 = "";
                List<RiwaRiskWaringRule> riskWaringRuleList = riskWaringRuleMapper.getWaringRuleByStatusId(waringStatus.getId());
                for (RiwaRiskWaringRule riskWaringRule : riskWaringRuleList) {
                    String s = "";
                    List<RiwaRiskWaringTarget> waringTargetList = riskWaringTargetMapper.getWaringTargetByRuleId(riskWaringRule.getId());
                    Iterator<RiwaRiskWaringTarget> iterator = waringTargetList.iterator();
                    while (iterator.hasNext()) {
                        RiwaRiskWaringTarget t = iterator.next();
                        if ("C".equals(t.getQuantityFlag())) {
                            s += t.getTargetName() + "" + t.getDdTypeName() + ",";
                        } else {
                            s += (t.getMinLimit() != null ? t.getMinLimit().setScale(2, BigDecimal.ROUND_HALF_DOWN) + ("Y".equals(t.getMinLimitMark()) ? "≤" : "＜") : "") +
                                    t.getTargetName() +
                                    (t.getMaxLimit() != null ? ("Y".equals(t.getMaxLimitMark()) ? "≤" : "＜") + t.getMaxLimit().setScale(2, BigDecimal.ROUND_HALF_DOWN) : "") + (iterator.hasNext() ? " 且 " : "");
                        }
                    }
                    s1 += s + ",";
                }
                String s2 = StringUtils.isNotEmpty(s1)? s1.substring(0, s1.length() - 1) : "";
                statusMap.put("waringStatusDesc", zhaunhuan(s2));
                statusList.add(statusMap);
            }
        }

        map.put("list", list);
        map.put("statusList", statusList);
        return map;
    }

    private List<Map<String, Object>> eventListData(String statusId){
        //本期风险事件披露
        List<RireRiskEvent> eventList = rireRiskEventMapper.getEventByImportId(statusId);
        List<Map<String, Object>> eventMapList = new ArrayList<>();

        int index = 0;
        if (CollectionUtils.isNotEmpty(eventList)) {
            for (RireRiskEvent event : eventList) {
                index++;
                Map<String, Object> eventMap = new HashMap<>();
                StringBuilder headContent=new StringBuilder();
                StringBuilder content=new StringBuilder();
                headContent.append(index).append("、");
                headContent.append("事件描述：");
                content.append(StringUtils.isEmpty(event.getEventDesc()) ? "":zhaunhuan(event.getEventDesc()));
                content.append("<w:br/>\t\t");
                eventMap.put("headContent",headContent.toString());
                eventMap.put("eventDescContent",content.toString());

                StringBuilder effectDescHeadContent=new StringBuilder();
                StringBuilder effectDesccontent=new StringBuilder();
                effectDescHeadContent.append("产生的影响：");
                effectDesccontent.append(StringUtils.isEmpty(event.getEffectDesc()) ? "":zhaunhuan(event.getEffectDesc()));
                effectDesccontent.append("<w:br/>\t\t");
                eventMap.put("effectDescHeadContent",effectDescHeadContent.toString());
                eventMap.put("effectDesccontent",effectDesccontent.toString());

                StringBuilder strategyHeadContent=new StringBuilder();
                StringBuilder strategycontent=new StringBuilder();
                strategyHeadContent.append("应对措施：");
                strategycontent.append(StringUtils.isEmpty(event.getStrategy()) ? "":zhaunhuan(event.getStrategy()));
                eventMap.put("strategyHeadContent",strategyHeadContent.toString());
                eventMap.put("strategycontent",strategycontent.toString());
                eventMapList.add(eventMap);
            }
        }
        return eventMapList;
    }

    @Override
    public Map reportTopWord(List<String> reportIds) throws Exception {
        Map map = new HashMap();
        RiriRisk status = ririRiskMapper.selectByPrimaryKey(reportIds.get(0));
        //RireRiskWarningStatus status = rireRiskWarningStatusMapper.selectByPrimaryKey(reportIds.get(0));
        //全年重点风险
        RiimRiskImportVO riskImport = new RiimRiskImportVO();
        riskImport.setAcctYear(status.getAcctYear());
        riskImport.setIsOverTheYears("Y");
        List<RiimRiskImport> importList = riskImportMapper.selectList(riskImport);

        //部门top3风险评估
        List<RiriRisk> riskList = Lists.newArrayList();
        //查询所有参与自评的单位
        List<XtzyCompany> riskCompany = xtzyCompanyService.selectCompanyByRisk(status.getManageCompCode());
        for (XtzyCompany xtzyCompany : riskCompany) {
            RiskTopThreeVO riskTopThree = new RiskTopThreeVO();
            riskTopThree.setAcctYear(status.getAcctYear());
            riskTopThree.setQuarterCurrent(status.getQuarterCurrent());
            riskTopThree.setCompCode(xtzyCompany.getCompCode());
            //查询本单位及下属子公司的风险自评top3
            List<RiriRisk> risks = ririRiskService.getTopThree(riskTopThree);
            if (CollectionUtils.isNotEmpty(risks)) {
                riskList.addAll(risks);
            } else {
                // 该单位零报告
                RiriRisk ririRisk = new RiriRisk();
                ririRisk.setDeptName(xtzyCompany.getCompName());
                ririRisk.setExt1("zero");
                riskList.add(ririRisk);
            }
        }

        List<Map> rlist = new ArrayList<>();
        int index = 0;
        if (CollectionUtils.isNotEmpty(riskList)) {
            for (RiriRisk risk : riskList) {
                Map rMap = new HashMap();
                rMap.put("index", index += 1);
                rMap.put("deptName", StringUtils.isEmpty(risk.getDeptName()) ? " " : zhaunhuan(risk.getDeptName()).replaceAll("\u001C", ""));
                rMap.put("aa", "/");
                if ("zero".equals(risk.getExt1())) {
                    // 零报告
                    rMap.put("riskName", "零报告");
                    rMap.put("riskDesc", "/");
                    rMap.put("remark", "/");
                } else {
                    rMap.put("riskName", StringUtils.isEmpty(risk.getRiskName()) ? " " : zhaunhuan(risk.getRiskName()).replaceAll("\u001C", ""));
                    rMap.put("riskDesc", StringUtils.isEmpty(risk.getRiskDesc()) ? " " : zhaunhuan(risk.getRiskDesc()).replaceAll("\u001C", ""));
                    rMap.put("remark", StringUtils.isEmpty(risk.getRemark()) ? " " : zhaunhuan(risk.getRemark()).replaceAll("\u001C", ""));
                }
                rlist.add(rMap);
            }

        } else {
            Map rMap = new HashMap();
            rMap.put("index", "/");
            rMap.put("deptName", "/");
            rMap.put("riskName", "/");
            rMap.put("riskDesc", "/");
            rMap.put("remark", "/");
            rMap.put("aa", "/");
            rlist.add(rMap);
        }
        map.put("r", rlist);

        map.put("acctYear", status.getAcctYear());
        map.put("quarter", status.getQuarterCurrent());
        //map.put("date", zhaunhuan(DateUtils.format(new Date(), "yyyy年MM月dd日")));
        return map;
    }

    public String zhaunhuan(String goal) {
        if (StringUtils.isNotEmpty(goal)) {
            String result = goal.replaceAll("&", "&amp;")
                    .replaceAll("<", "&lt;")
                    .replaceAll(">", "&gt;")
                    .replaceAll("\"", "&quot;")
                    ;
            return result;
        }else{
            return "";
        }
    }

    private String pageSplit = "<w:p><w:pPr><w:keepNext w:val=\"off\"/><w:keepLines w:val=\"off\"/><w:pageBreakBefore w:val=\"off\"/><w:widowControl w:val=\"off\"/><w:tabs><w:tab w:val=\"center\" w:pos=\"4153\"/><w:tab w:val=\"right\" w:pos=\"8306\"/></w:tabs><w:kinsoku/><w:wordWrap/><w:overflowPunct/><w:topLinePunct w:val=\"off\"/><w:autoSpaceDE/><w:autoSpaceDN/><w:adjustRightInd/><w:snapToGrid w:val=\"off\"/><w:spacing w:before=\"156\" w:before-lines=\"50\" w:after=\"0\" w:after-lines=\"0\" w:line=\"240\" w:line-rule=\"at-least\"/><w:ind w:left=\"0\" w:left-chars=\"0\" w:right=\"0\" w:right-chars=\"0\" w:first-line=\"0\" w:first-line-chars=\"0\"/><w:jc w:val=\"both\"/><w:textAlignment w:val=\"auto\"/><w:outlineLvl w:val=\"9\"/><w:rPr><w:rFonts w:ascii=\"微软雅黑\" w:h-ansi=\"微软雅黑\" w:fareast=\"微软雅黑\" w:cs=\"微软雅黑\" w:hint=\"fareast\"/><w:b w:val=\"off\"/><w:color w:val=\"auto\"/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:ascii=\"微软雅黑\" w:h-ansi=\"微软雅黑\" w:fareast=\"微软雅黑\" w:cs=\"微软雅黑\" w:hint=\"default\"/><w:b w:val=\"off\"/><w:color w:val=\"auto\"/><w:lang w:fareast=\"ZH-CN\"/></w:rPr><w:br w:type=\"page\"/></w:r></w:p>";
    private String colorTemplate = "<w:r><w:rPr><w:rFonts w:ascii=\"楷体\" w:h-ansi=\"楷体\" w:fareast=\"楷体\" w:cs=\"楷体\" w:hint=\"fareast\"/><w:color w:val=\"000000\"/><w:sz w:val=\"28\"/><w:sz-cs w:val=\"28\"/><w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"${color}\"/></w:rPr><w:t>${colorName}</w:t></w:r>";
    private Map<String, String> colorMap = ImmutableMap.of(
            "green", "绿灯",
            "yellow","黄灯",
            "orange","橙灯",
            "red","红灯",
            "black","黑灯"
    );
    private Map<String, String> colorMap2 = ImmutableMap.of(
            "green", "绿灯",
            "yellow","黄灯",
            "orange","橙灯",
            "red","红灯",
            "black","黑灯"
    );
    private Map<String, String> conclusionMap = ImmutableMap.of(
            "green", "绿灯",
            "yellow","黄灯",
            "red","红灯",
            "orange","橙灯"
    );

    private String getColorName(String color) {
        return getColorName(color, colorMap);
    }

    private String getColorName(String color, Map<String, String> colorMap) {
        if (StringUtils.isEmpty(color)) {
            color = "/";
        }
        String result = "";
        switch (color) {
            case "green":
                result = colorTemplate.replace("${color}", "00FF00").replace("${colorName}", colorMap.get(color));
                break;
            case "yellow":
                result = colorTemplate.replace("${color}", "FFFF00").replace("${colorName}", colorMap.get(color));
                break;
            case "orange":
                result = colorTemplate.replace("${color}", "CC7033").replace("${colorName}", colorMap.get(color));
                break;
            case "red":
                result = colorTemplate.replace("${color}", "FF0000").replace("${colorName}", colorMap.get(color));
                break;
            case "black":
                result = colorTemplate.replace("${color}", "7F7F7F").replace("${colorName}", colorMap.get(color));
                break;
            default:
//                result = colorTemplate.replace("${color}", "FFFFFF").replace("${colorName}", color);
                result = colorTemplate.replace("${color}", "FFFFFF").replace("${colorName}", "");
                break;
        }
        return result;
    }

    private String getImageStr(String path) throws IOException {
        InputStream in = null;
        byte[] data = null;
        try {
            File imgFile = new File(path);
            if (imgFile != null && imgFile.exists()) {
                in = new FileInputStream(imgFile);
                data = new byte[in.available()];
                in.read(data);
                BASE64Encoder encoder = new BASE64Encoder();
                return encoder.encode(data);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (in != null) in.close();
        }
        return "";
    }


}
